package com.example.a0521.fragments;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.a0521.AlbumAdpater;
import com.example.a0521.R;
import com.example.a0521.pojo.Album;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AlbumlistFragment extends Fragment {
    private List<Album> albums = new ArrayList<>();
    private AlbumAdpater adpater;

    public AlbumlistFragment() {
        super(R.layout.fragment_album_list);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ListView lv = view.findViewById(R.id.lv);
        adpater = new AlbumAdpater(getContext(), R.layout.listview_album, albums);
        lv.setAdapter(adpater);
    }

    public void fetchMusic() {
        OkHttpClient client = new OkHttpClient();
        try {
            Request request = new Request.Builder().url("http://johnyu.cn:3000/albums").build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {

                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        String message = response.body().string();
                        JSONArray array = new JSONArray(message);
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = array.getJSONObject(i);
                            Integer id = obj.getInt("id");
                            String name = obj.getString("name");
                            double price = obj.getDouble("price");
                            Album album = new Album(id, name, price);
                            albums.add(album);
                            AlbumlistFragment.this
                                    .getActivity()
                                    .runOnUiThread(() -> adpater.notifyDataSetChanged());

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });


        } catch (Exception e) {
            System.out.println("异常结束");
            e.printStackTrace();
        }
    }
}
